package br.com.pnfp.web.model.dao;

import java.lang.reflect.Field;

import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import br.com.pnfp.web.model.vo.ValueObject;

@Aspect
public class DAOAspect {

	@Before("execution(* br.com.pnfp.web.model.dao.mysql.*.*(..)) && args(bean,..)")
	public void doAccessCheck(Object bean) throws Exception {
		processToUpperCase(bean);		
	}
	
	private void processToUpperCase(Object bean) throws Exception {
		if(bean instanceof ValueObject) {
			Field[] fields = bean.getClass().getDeclaredFields();
			for(Field field : fields) {
				if(field.getName().equals("serialVersionUID"))
					continue;
				Object value = BeanUtils.getProperty(bean, field.getName());
				if(field.getType().equals(String.class)) {
					if(value != null) {
						String strValue = (String) value;
						String converted = strValue;//new String(strValue.getBytes("ISO-8859-1"));
						if(!field.getName().endsWith("senha")) {
							converted = converted.toUpperCase();
						}
						BeanUtils.setProperty(bean, field.getName(), converted);
					}
				} else {
					if(value instanceof ValueObject) {
						processToUpperCase(value);
					}
				}
			}
		}
	}	
}
